package com.kocel.block.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.kocel.block.model.TbBlockInventory;
import com.kocel.block.model.TbBlockRecord;
import com.kocel.block.model.TbUser;
import com.kocel.block.model.smelt_pouring_history;
import com.kocel.block.repository.TbBlockRecordRepository;
import com.kocel.block.service.BlockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/blockInventory")
public class BlockController {

    @Autowired
    private BlockService blockService;



    @RequestMapping(method = RequestMethod.POST,value = "/listInventory")
    public String listInventory( Optional<String> productName, Optional<String> blockNumber, Optional<String> meltingStove, HttpServletRequest request) {

        Map<String, Object> model = new HashMap<String, Object>();
        List<TbBlockInventory> list = blockService.getInventoryList(productName.orElse(""),blockNumber.orElse(""),meltingStove.orElse(""));
        model.put("list", list);
        String retJson = JSON.toJSONString(model, SerializerFeature.DisableCircularReferenceDetect);
        return retJson;
    }

    @RequestMapping(value = "/listPouring",method = RequestMethod.POST)
    public String listPouring(Optional<String> meltingStove,Optional<String> meltingWrap,Optional<String> texture) {
        Map<String, Object> model = new HashMap<String, Object>();
        List<smelt_pouring_history> list = blockService.findAllByView(meltingStove.orElse(""), meltingWrap.orElse(""), texture.orElse(""));
        model.put("list", list);
        String retJson = JSON.toJSONString(model, SerializerFeature.DisableCircularReferenceDetect);
        return retJson;
    }

    @RequestMapping(value = "/isExistedBlockNo",method = RequestMethod.POST)
    public String isExistedBlockNo(Optional<String> blockNo){
        Map<String, Object> model = new HashMap<String, Object>();
        boolean ret = blockService.isExistedBlockNo(blockNo.orElse(""));
        model.put("success", ret);
        String retJson = JSON.toJSONString(model, SerializerFeature.DisableCircularReferenceDetect);
        return retJson;
    }

    @RequestMapping(value = "/saveBlock",produces = "text/html;charset=UTF-8")
    public String saveBlock(
            Optional<String> meltingStove,
            Optional<String> meltingWrap,
            Optional<String> texture,
            Optional<String> pureTime,
            Optional<String> location,
            Optional<String> blockType,
            Optional<String> number,
            Optional<String> userId,
            Optional<String> blockNo,
            Optional<String> deadline) {

        Map<String, Object> model = new HashMap<String, Object>();

        //TbUser user= blockService.getTbUserRepository().findById(userId.orElse("")).get();

        List<smelt_pouring_history> productNames = null;

        if(texture.equals("灰铁") || texture.equals("蠕铁")) {
            productNames = blockService.findAllByMeltingWrap(meltingWrap.orElse(""));
        } else {
            productNames = blockService.findAllByMeltingStove(meltingStove.orElse(""));
        }

        String productName = "";
        String castingNum = "";
        String figureNumber = "";

        for(smelt_pouring_history p : productNames) {
            if(productName.equals("")) {
                productName += p.getProductName();
            } else {
                if(!productName.contains(p.getProductName())) {
                    productName += "," + p.getProductName();
                }
            }

            if(figureNumber.equals("")) {
                figureNumber += p.getGradeNum();
            }
            else {
                if(!figureNumber.contains(p.getGradeNum())) {
                    figureNumber += "," + p.getGradeNum();
                }
            }

            if(castingNum.equals("")) {
                castingNum += p.getPieceNo();
            }
            else {
                if(!castingNum.contains(p.getPieceNo())) {
                    castingNum += "," + p.getPieceNo();
                }
            }
        }

        TbBlockInventory block = new TbBlockInventory();
        block.setBlockLocation(location.orElse(""));
        block.setBlockNumber(blockNo.orElse(""));
        block.setBlockType(blockType.orElse(""));
        block.setCastingNum(castingNum);
        block.setCustomer("");
        block.setFigureNumber(figureNumber);
        block.setInventryNum(Double.valueOf(number.orElse("0")));
        block.setProduct(productName);
        block.setState("0");
        block.setMeltingStove(meltingStove.orElse(""));
        block.setMeltingWrap(meltingWrap.orElse(""));
        DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        Date now = new Date();
        String time=format.format(now);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        // System.out.println(sdf.format(calendar.getTime()));
        calendar.add(Calendar.MONTH, Integer.parseInt(deadline.orElse("0")));
        System.out.println(format.format(calendar.getTime()));
        block.setStorageTime(time);
        block.setTexture(texture.orElse(""));
        block.setUserId(userId.get());
        block.setDeadline(Integer.parseInt(deadline.orElse("")));
        block.setDestroyTime(format.format(calendar.getTime()));
        blockService.getTbBlockInventoryRepository().save(block);
        String retJson = JSON.toJSONString(model, SerializerFeature.DisableCircularReferenceDetect);
        return retJson;
    }

    @RequestMapping(value = "/listOutBlock",method = RequestMethod.POST)
    public String listOutBlock(Optional<String> blockNumber) {
        Map<String, Object> model = new HashMap<String, Object>();
        List<TbBlockInventory> list = blockService.getTbBlockInventoryListForOut(blockNumber.orElse(""));
        model.put("list", list);
        String retJson = JSON.toJSONString(model, SerializerFeature.DisableCircularReferenceDetect);
        return retJson;
    }

    @RequestMapping(value = "/saveOutBlock",method = RequestMethod.POST)
    public String saveOutBlock(Optional<String> reason,Optional<String> number,Optional<String> userId,Optional<String> objId) {
        Map<String, Object> model = new HashMap<String, Object>();

        TbBlockInventory block = blockService.getTbBlockInventoryRepository().findById(objId.get()).orElse(new TbBlockInventory());
        TbBlockRecord blockRecord = new TbBlockRecord();
        //blockRecord.setBlockId(objId.get());
        blockRecord.setOutNum(Double.valueOf(number.orElse("0")));
        blockRecord.setUserId(userId.get());
        blockRecord.setState("0");
        blockRecord.setReason(reason.orElse(""));
        DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        String time=format.format(new Date());
        blockRecord.setOutStorageTime(time);
        blockRecord.setTbBlockInventory(block);
        blockService.getTbBlockRecordRepository().save(blockRecord);
        block.setInventryNum(block.getInventryNum()-blockRecord.getOutNum());
        blockService.getTbBlockInventoryRepository().save(block);
        String retJson = JSON.toJSONString(model, SerializerFeature.DisableCircularReferenceDetect);
        return retJson;
    }

    @RequestMapping(value = "/listBlockRecord",method = RequestMethod.POST)
    public String listBlockRecord(Optional<String> blockNumber ) {
        Map<String, Object> model = new HashMap<String, Object>();
        List<TbBlockRecord> list = blockService.getTbBlockRecordList(blockNumber.orElse(""));
        model.put("list", list);
        String retJson = JSON.toJSONString(model, SerializerFeature.DisableCircularReferenceDetect);
        return retJson;
    }

    @RequestMapping(value = "/receiveBlock",method = RequestMethod.POST)
    public String receiveBlock(Optional<String> objId) {
        Map<String, Object> model = new HashMap<String, Object>();

        TbBlockRecord blockRecord= blockService.getTbBlockRecordRepository().findById(objId.get()).get();
        blockRecord.setState("1");//检测接收
        DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        String time=format.format(new Date());
        blockRecord.setReceiveTime(time);
        blockService.getTbBlockRecordRepository().save(blockRecord);
        String retJson = JSON.toJSONString(model, SerializerFeature.DisableCircularReferenceDetect);
        return retJson;
    }

    @RequestMapping(value = "/listBlockDestroy",method = RequestMethod.POST)
    public String listBlockDestroy(Optional<String> blockNumber) {
        Map<String, Object> model = new HashMap<String, Object>();
        List<TbBlockInventory> list = blockService.getTbBlockInventoryListForDestroy(blockNumber.orElse(""));
        model.put("list", list);
        String retJson = JSON.toJSONString(model, SerializerFeature.DisableCircularReferenceDetect);
        return retJson;
    }

    @RequestMapping(value = "/destroyBlock",method = RequestMethod.POST)
    public String destroyBlock(Optional<String> objId) {
        Map<String, Object> model = new HashMap<String, Object>();
        TbBlockInventory block= blockService.getTbBlockInventoryRepository().findById(objId.get()).get();
        block.setState("1");//已销毁
        DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        String time=format.format(new Date());
        block.setActualDestroyTime(time);;
        blockService.getTbBlockInventoryRepository().save(block);
        String retJson = JSON.toJSONString(model, SerializerFeature.DisableCircularReferenceDetect);
        return retJson;
    }

    @RequestMapping(value = "/listBlockRecordByMachining",method = RequestMethod.POST)
    public String listBlockRecordByMachining(Optional<String> blockNumber) {
        Map<String, Object> model = new HashMap<String, Object>();
        List<TbBlockRecord> list = blockService.getTbBlockRecordMatchingList(blockNumber.orElse(""));
        model.put("list", list);
        String retJson = JSON.toJSONString(model, SerializerFeature.DisableCircularReferenceDetect);
        return retJson;
    }

    @RequestMapping(value = "/maReceiveBlock",method = RequestMethod.POST)
    public String maReceiveBlock(Optional<String> objId) {
        Map<String, Object> model = new HashMap<String, Object>();
        TbBlockRecord blockRecord= blockService.getTbBlockRecordRepository().findById(objId.get()).get();
        blockRecord.setState("2");//加工接收
        DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        String time=format.format(new Date());
        blockRecord.setMachiningReceiveTime(time);
        blockService.getTbBlockRecordRepository().save(blockRecord);
        String retJson = JSON.toJSONString(model, SerializerFeature.DisableCircularReferenceDetect);
        return retJson;
    }

    @RequestMapping(value = "/listBlockRecordByCheck",method = RequestMethod.POST)
    public String listBlockRecordByCheck(Optional<String> blockNumber ) {
        Map<String, Object> model = new HashMap<String, Object>();
        List<TbBlockRecord> list = blockService.getTbBlockRecordCheckList(blockNumber.orElse(""));
        model.put("list", list);
        String retJson = JSON.toJSONString(model, SerializerFeature.DisableCircularReferenceDetect);
        return retJson;
    }

    @RequestMapping(value = "/confirmReceive",method = RequestMethod.POST)
    public String confirmReceive(Optional<String> objId ,Optional<String> isqualify) {
        Map<String, Object> model = new HashMap<String, Object>();
        TbBlockRecord blockRecord= blockService.getTbBlockRecordRepository().findById(objId.get()).get();
        blockRecord.setState("3");//检测确认
        blockRecord.getTbBlockInventory().setIsqualify(isqualify.get());

        if(isqualify.get().equals("不合格")){
            List<TbBlockInventory> tbilist = blockService.getTbBlockInventoryRepository().findAllByMeltingStove(blockRecord.getTbBlockInventory().getMeltingStove());

            for(TbBlockInventory tb : tbilist)
            {
                tb.setRemark("复检");
                blockService.getTbBlockInventoryRepository().save(tb);
            }
        }



        DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        String time=format.format(new Date());
        blockRecord.setCheckConfirmTime(time);
        blockService.getTbBlockRecordRepository().save(blockRecord);
        String retJson = JSON.toJSONString(model, SerializerFeature.DisableCircularReferenceDetect);
        return retJson;
    }

    @RequestMapping(value = "/listBlockRecordByOutSourcing",method = RequestMethod.POST)
    public String listBlockRecordByOutSourcing(Optional<String> blockNumber ) {
        Map<String, Object> model = new HashMap<String, Object>();
        List<TbBlockRecord> list = blockService.getTbBlockRecordOutList(blockNumber.orElse(""));
        model.put("list", list);
        String retJson = JSON.toJSONString(model, SerializerFeature.DisableCircularReferenceDetect);
        return retJson;
    }

    @RequestMapping(value = "/outSourcingBlock",method = RequestMethod.POST)
    public String outSourcingBlock(Optional<String> objId ) {
        Map<String, Object> model = new HashMap<String, Object>();
        TbBlockRecord blockRecord= blockService.getTbBlockRecordRepository().findById(objId.get()).get();
        blockRecord.setState("4");//委外出库
        DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        String time=format.format(new Date());
        blockRecord.setOutSourcingTime(time);
        blockService.getTbBlockRecordRepository().save(blockRecord);
        String retJson = JSON.toJSONString(model, SerializerFeature.DisableCircularReferenceDetect);
        return retJson;
    }

    @RequestMapping(value = "/listOutSourcingByReturn",method = RequestMethod.POST)
    public String listOutSourcingByReturn(Optional<String> blockNumber ) {
        Map<String, Object> model = new HashMap<String, Object>();
        List<TbBlockRecord> list = blockService.getTbBlockRecordOutReturnList(blockNumber.orElse(""));
        model.put("list", list);
        String retJson = JSON.toJSONString(model, SerializerFeature.DisableCircularReferenceDetect);
        return retJson;
    }

    @RequestMapping(value = "/outSourcingReturn",method = RequestMethod.POST)
    public  String outSourcingReturn(Optional<String> objId) {
        Map<String, Object> model = new HashMap<String, Object>();
        TbBlockRecord blockRecord= blockService.getTbBlockRecordRepository().findById(objId.get()).get();
        blockRecord.setState("5");//委外出库
        DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        String time=format.format(new Date());
        blockRecord.setOutSouringReceiveTime(time);
        blockService.getTbBlockRecordRepository().save(blockRecord);
        String retJson = JSON.toJSONString(model, SerializerFeature.DisableCircularReferenceDetect);
        return retJson;
    }

    @RequestMapping(value = "/getBlockById",method = RequestMethod.POST)
    public  String getBlockById(Optional<String> objId ) {
        Map<String, Object> model = new HashMap<String, Object>();
        TbBlockInventory block = blockService.getTbBlockInventoryRepository().findById(objId.get()).orElse(new TbBlockInventory());

        //List<TbBlockInventory> list = new ArrayList<TbBlockInventory>();
        //list.add(block);
        model.put("list", block);
        String retJson = JSON.toJSONString(model, SerializerFeature.DisableCircularReferenceDetect);
        return retJson;
    }

    @RequestMapping(value = "/updateBlock",method = RequestMethod.POST)
    public  String updateBlock(Optional<String> location,Optional<String> blockType,Optional<String> number,Optional<String> objId,Optional<String> blockNo,Optional<String> deadline ) {
        Map<String, Object> model = new HashMap<String, Object>();
        TbBlockInventory block = blockService.getTbBlockInventoryRepository().findById(objId.get()).orElse(new TbBlockInventory());
        block.setBlockLocation(location.orElse(""));
        block.setBlockNumber(blockNo.orElse(""));
        block.setBlockType(blockType.orElse(""));

        block.setInventryNum(Double.valueOf(number.orElse("0")));
        DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        Date now = new Date();
        String time=format.format(now);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        // System.out.println(sdf.format(calendar.getTime()));
        calendar.add(Calendar.MONTH, Integer.parseInt(deadline.orElse("0")));
        System.out.println(format.format(calendar.getTime()));
        block.setStorageTime(time);

        block.setDeadline(Integer.parseInt(deadline.orElse("0")));
        block.setDestroyTime(format.format(calendar.getTime()));
        blockService.getTbBlockInventoryRepository().save(block);
        String retJson = JSON.toJSONString(model, SerializerFeature.DisableCircularReferenceDetect);
        return retJson;
    }
}
